package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.*;
import com.zhentao.pojo.*;
import com.zhentao.service.DoctorService;
import com.zhentao.vo.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author ls
* @description 针对表【doctor】的数据库操作Service实现
* @createDate 2025-05-07 21:25:14
*/
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService{
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private DoctorPatientMapper doctorPatientMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private MedicalDrugsMapper medicalDrugsMapper;
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;
    @Autowired
    private DrugsMapper drugsMapper;


    @Override
    public Page<Doctor> findPage(QueryParam queryParam) {
        Page<Doctor> page = new Page<>(queryParam.getCurrent(), queryParam.getSize());
        QueryWrapper<Doctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(queryParam.getDname()!=null,"dname",queryParam.getDname());
        doctorMapper.selectPage(page,queryWrapper);
        List<Doctor> records = page.getRecords();
        if (records != null){
            for (Doctor record : records) {
                Integer departmentid = record.getDepartmentid();
                Integer rid = record.getRid();
                record.setDepartment(departmentMapper.selectById(departmentid));
                record.setRole(roleMapper.selectById(rid));
            }
            return page;
        }
        return null;
    }

    @Override
    public List<Patient> findPatient(Integer doctorId) {
        QueryWrapper<DoctorPatient> wrapper = new QueryWrapper<>();
        wrapper.eq("did", doctorId);
        List<DoctorPatient> relations = doctorPatientMapper.selectList(wrapper);

        List<Patient> patients = new ArrayList<>();
        for (DoctorPatient relation : relations) {
            Patient patient = patientMapper.selectById(relation.getPid());
            if (patient != null) {
                // 查询患者所有订单（原逻辑）
                QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("patient_id", patient.getId());
                List<Order> orders = orderMapper.selectList(orderWrapper);
                List<Map<String, Object>> orderDetails = processOrders(orders);
                patient.setOrderDetails(orderDetails);

                // 新增：查询患者所有病历记录
                QueryWrapper<MedicalRecord> recordWrapper = new QueryWrapper<>();
                recordWrapper.eq("patient_id", patient.getId());
                List<MedicalRecord> medicalRecords = medicalRecordMapper.selectList(recordWrapper);

                // 处理每个病历的药品信息
                List<Map<String, Object>> medicalDetails = new ArrayList<>();
                for (MedicalRecord record : medicalRecords) {
                    Map<String, Object> medicalDetail = new HashMap<>();

                    // 查询病历关联的药品
                    QueryWrapper<MedicalDrugs> drugsWrapper = new QueryWrapper<>();
                    drugsWrapper.eq("record_id", record.getRecordId());
                    List<MedicalDrugs> medicalDrugs = medicalDrugsMapper.selectList(drugsWrapper);

                    // 获取药品详细信息
                    List<Map<String, Object>> drugDetails = new ArrayList<>();
                    for (MedicalDrugs md : medicalDrugs) {
                        Drugs drug = drugsMapper.selectById(md.getDrugId());
                        if (drug != null) {
                            Map<String, Object> drugInfo = new HashMap<>();
                            drugInfo.put("medicalDrug", md); // 包含数量、用法
                            drugInfo.put("drugDetail", drug); // 药品详细信息
                            drugDetails.add(drugInfo);
                        }
                    }

                    medicalDetail.put("medicalRecord", record); // 病历基本信息
                    medicalDetail.put("drugs", drugDetails);    // 关联的药品详细信息
                    medicalDetails.add(medicalDetail);
                }

                // 将病历及药品数据存入临时字段（需在Patient实体类中添加medicalDetails字段）
                patient.setMedicalDetails(medicalDetails);
                patients.add(patient);
            }
        }
        return patients;
    }

    // 原订单处理逻辑封装为方法
    private List<Map<String, Object>> processOrders(List<Order> orders) {
        List<Map<String, Object>> orderDetails = new ArrayList<>();
        for (Order order : orders) {
            Map<String, Object> detail = new HashMap<>();
            DoctorSchedule schedule = doctorScheduleMapper.selectById(order.getDoctorScheduleId());
            QueryWrapper<Source> sourceWrapper = new QueryWrapper<>();
            sourceWrapper.eq("schedule_id", order.getDoctorScheduleId());
            List<Source> sources = sourceMapper.selectList(sourceWrapper);
            detail.put("order", order);
            detail.put("schedule", schedule);
            detail.put("sources", sources);
            orderDetails.add(detail);
        }
        return orderDetails;
    }


}




